package cn.itcast.controller;

import cn.itcast.common.R;
import cn.itcast.entity.AddressBook;
import cn.itcast.service.IAddressService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/addressBook")
public class AddressController  extends BaseController{
    @Autowired
     private IAddressService addressService;


    @GetMapping("list")
    public R<List<AddressBook>> list(){
        Long userId = (Long) session.getAttribute("LOGIN_ID");
        System.err.println(userId);
        List<AddressBook> list = addressService.list(userId);
        return R.success(list);
    }

    @PostMapping
    public R<String> save(@RequestBody AddressBook addressBook){
        Long userId = (Long) session.getAttribute("LOGIN_ID");
        addressBook.setUserId(userId);
          addressService.save(addressBook);
        return R.success("添加成功");
    }

    /**
     * 更新默认的地址
     * @param addressBook
     * @return
     */
    @PutMapping("default")
    public R<String> updateDefaultAddr(@RequestBody AddressBook addressBook){
        Long userId = (Long) session.getAttribute("LOGIN_ID");
        addressBook.setUserId(userId);
        addressService.updateDefaultAddr(addressBook);

        return R.success("修改成功");
    }
    /**
     * 修改地址回显
     */
    @GetMapping("{id}")
    public R<AddressBook> echoAddr(@PathVariable Long id){
        AddressBook addressBook =addressService.getById(id);
     return R.success(addressBook);
    }


    @PutMapping
    public R<String> updateAddr(@RequestBody AddressBook addressBook){
          addressService.updateAddr(addressBook);
        return R.success("修改成功");
    }

    @DeleteMapping
    public R<String> deleteAddr(Long ids){
        addressService.delete(ids);
        return R.success("删除成功");
    }
/**
 * 获得默认的地址
 */
@GetMapping("default")
public R<AddressBook> getDefaultAddr(){

    return R.success(addressService.getDefaultAddr());
}
}
